#coding=utf-8
import os, sys, datetime, time
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
os.environ['DJANGO_SETTINGS_MODULE'] = 'blackeyes.settings'
from django.db import IntegrityError
from tsina.dbserver.models import Message, User
import tsina
from config import keyword

today = datetime.date.today()
e = today.isoformat()
now = datetime.datetime.now()

logfile = os.path.join(PROJECT_ROOT, 'log/today_message.log')
l = open(logfile, 'a')
l.write('Tsina Robot started at %s\n'%now)
l.flush()

search_url = 'http://t.sina.com.cn/k/%s&page=%i'
t = tsina.t

n = 1000
for i in range(n):
  url = search_url%(keyword,i+1)
  now = datetime.datetime.now()
  code, r,c = t._get_url(url)
  ms = tsina.parse_search(c, now)

  for m in ms:
    d = m.created_at.date()
    if d < today:
      l.write('Tsina Robot quit\n')
      l.close()
      sys.exit()

    u = User.objects.get_or_create(user_id=m.owner_id)[0]
    try:
      mes, created = Message.objects.get_or_create(user=u, url_id=m.url_id, resource_id=m.resource_id, content=m.content, published_at=m.created_at)
    except IntegrityError:
      continue

